<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拖拽元素</title>
  </head>

  <body>
    <div style="width: 100px; height: 100px; background-color: red; position: absolute; left: 0; top: 0"></div>
    <script>
      var div = document.getElementsByTagName("div")[0];
      // var disX, disY;
      // div.onmousedown = function(e) {
      //     disX = e.pageX - parseInt(div.style.left);
      //     disY = e.pageY - parseInt(div.style.top);

      //     document.onmousemove = function(e) {
      //         var event = e || window.event;

      //         div.style.left = e.pageX - disX + 'px';
      //         div.style.top = e.pageY - disY + 'px';
      //     }

      //     div.onmouseup = function() {
      //         div.onmousemove = null;
      //     }
      // }

      function drag(ele) {
        var clickFlag = false;
        var disX;
        var disY;
        ele.addEventListener(
          "mousedown",
          function (e) {
            disX = e.pageX - parseInt(div.style.left);
            disY = e.pageY - parseInt(div.style.top);
            clickFlag = true;
          },
          false
        );
        document.addEventListener(
          "mousemove",
          function (e) {
            var event = e || window.event;
            if (clickFlag) {
              ele.style.left = e.pageX - disX + "px";
              ele.style.top = e.pageY - disY + "px";
            }
          },
          false
        );

        ele.addEventListener(
          "mouseup",
          function () {
            if (clickFlag) {
              ele.onmousemove = null;
              clickFlag = false;
            }
          },
          false
        );
      }

      drag(div);
    </script>
  </body>
</html>
